﻿using System.Linq;
using Mondial2014.Models.Context;
using Mondial2014.Models.Gambling;
using Mondial2014.Utils.Events;

namespace Mondial2014.Utils
{
    public static class GamblerScoreCalculator
    {
        private static readonly object Sync = new object();

        [EventDispatcher.Subscribe]
        public static void CalculateScores(MatchUpdatedEvent matchUpdatedEvent)
        {
            lock (Sync)
            {
                using (var context = new Mondial2014DbContext())
                {
                    var fixtures = context.Fixtures.Where(f => f.Played).ToArray();
                    var players = context.Gamblers.ToArray();

                    foreach (var player in players)
                    {
                        player.GroupsStageScore = 0;
                    }

                    foreach (var fixture in fixtures)
                    {
                        foreach (var player in players)
                        {
                            var gameGamble = context.GameGambles.Single(
                                gg => gg.Gambler.Id == player.Id && gg.Fixture.Number == fixture.Number);
                            if (gameGamble.FixtureResult == fixture.GetGameResult())
                            {
                                player.GroupsStageScore++;
                            }
                        }
                    }

                    context.SaveChanges();
                }
            }
        }
    }
}